import request from '@/utils/request'
import type { ApiResponse } from '@/utils/request'
import { get, del } from '@/utils/request'

// 群聊二维码类型定义
export interface QrCode {
  qrCodeId: number
  qrCodeUrl: string
  uploadTime: string
  expiryTime?: string
  status: string
  creatorName: string
  updaterName?: string
}

// 分页返回数据类型
export interface PageResult<T> {
  records: T[]
  total: number
  size: number
  current: number
  pages: number
}

// 上传群聊二维码
export function uploadQrCode(data: FormData): Promise<ApiResponse<QrCode>> {
  return new Promise((resolve, reject) => {
    request({
      url: '/system/qrcode/upload',
      method: 'post',
      data,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
      .then((res) => {
        resolve(res as unknown as ApiResponse<QrCode>)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

// 更新群聊二维码
export function updateQrCode(data: FormData): Promise<ApiResponse<boolean>> {
  return new Promise((resolve, reject) => {
    request({
      url: '/system/qrcode/update',
      method: 'put',
      data,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
      .then((res) => {
        resolve(res as unknown as ApiResponse<boolean>)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

// 删除群聊二维码
export function deleteQrCode(qrCodeId: number): Promise<ApiResponse<boolean>> {
  return del<boolean>(`/system/qrcode/${qrCodeId}`)
}

// 获取群聊二维码详情
export function getQrCodeDetail(qrCodeId: number): Promise<ApiResponse<QrCode>> {
  return get<QrCode>(`/system/qrcode/${qrCodeId}`)
}

// 分页获取群聊二维码列表
export interface QrCodeListQuery {
  current?: number
  size?: number
  status?: string
}

export function getQrCodeList(params: QrCodeListQuery): Promise<ApiResponse<PageResult<QrCode>>> {
  return get<PageResult<QrCode>>('/system/qrcode/list', params as Record<string, unknown>)
}

// 获取最新有效的群聊二维码
export function getLatestQrCode(): Promise<ApiResponse<QrCode>> {
  return get<QrCode>('/system/qrcode/latest')
}
